package com.my.swas.sso.module.api.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.swas.common.base.ResponseResult;
import com.my.swas.common.jwt.JWTToken;
import com.my.swas.common.jwt.JWTUtils;
import com.my.swas.common.utils.CacheUtils;
import com.my.swas.sso.common.constans.CacheConst;
import com.my.swas.common.constans.CommConst;
import com.my.swas.sso.module.admin.entity.User;
import com.my.swas.sso.enums.OperationType;
import com.my.swas.sso.module.admin.service.UserService;
import com.my.swas.sso.module.api.dto.LoginDto;
import io.swagger.annotations.Api;
import jodd.util.BCrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Description:
 * @author: :MaYong
 */
@Api(value = "授权管理",tags = "授权管理")
@Slf4j
@RestController
@RequestMapping("api/auth")
@ResponseBody
public class AuthApiController {
    @Resource
    UserService userService;
    @Resource
    CacheUtils cacheUtils;
    /**
     * 登录
     * @return
     */
    @PostMapping(value = "login")
    public ResponseResult login(@RequestBody LoginDto loginDto){
        String username = StrUtil.isNotBlank(loginDto.getUsername())?loginDto.getUsername():loginDto.getEmail();
        String password = loginDto.getPassword();
        User userBean = userService.getOne(new QueryWrapper<User>().lambda()
                .eq(User::getUserAccount,username));
        if (userBean == null) {
            return ResponseResult.error("系统不存在该账户，请注册属于自己的账户");
        }
        /*验证帐号是否已经锁定*/
        if (CommConst.NO.equals(userBean.getEnable())) {
            return ResponseResult.error("账户已经锁定，请联系管理员解锁");
        }
        /*验证错误登录次数*/
        if (null != userBean.getVerifyCount()) {
            if (CommConst.FIVE.compareTo(userBean.getVerifyCount()) <= 0) {
                return ResponseResult.error("密码错误次数超出上限，账号已被锁定，请联系管理员！");
            }
        }
        /*判断密码是否正确*/
        if (!BCrypt.checkpw(password, userBean.getPassword())) {
            userService.verifyCount(userBean.getId(), userBean.getVerifyCount(), OperationType.PLUS);
            return ResponseResult.error("请填写正确的用户名和密码");
        }
        /*下面可以直接返回jwtToken.但是为了更好的理解和应用加一层利用shiro验证机制登录的逻辑*/
        String sign = JWTUtils.sign(userBean.getUserAccount(), userBean.getPassword(), userBean.getId());
        /*获取当前的Subject*/
        Subject subject = SecurityUtils.getSubject();
        JWTToken jwtToken = new JWTToken(sign);
        try {
            log.debug("对用户[" + username + "]进行登录验证..验证开始");
            subject.login(jwtToken);
        } catch (Exception uae) {
            return ResponseResult.error("请填写正确的用户名和密码");
        }
        /*验证是否登录成功*/
        if (subject.isAuthenticated()) {
            log.debug("用户[" + username + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)");
            cacheUtils.setStr(CacheConst.EH_SSO_USER+userBean.getId(), JSONObject.toJSONString(userBean));
            userService.verifyCount(userBean.getId(), userBean.getVerifyCount(), OperationType.ZERO);
            /*refreshMainTree(jwtToken);*/
        } else {
            jwtToken.clear();
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",jwtToken.getPrincipal());
        return ResponseResult.ok("授权登录成功！",jsonObject);
    }


}
